using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Net;
using System.Threading;
using System.Threading.Tasks;
using AzureTelemetryBlob;
using Microsoft.WindowsAzure;
using Microsoft.WindowsAzure.Diagnostics;
using Microsoft.WindowsAzure.ServiceRuntime;
using Microsoft.WindowsAzure.Storage;

namespace WorkerRole1
{
    public class WorkerRole : RoleEntryPoint
    {
        private readonly CancellationTokenSource cancellationTokenSource = new CancellationTokenSource();
        private readonly ManualResetEvent runCompleteEvent = new ManualResetEvent(false);

        public override void Run()
        {
            Trace.TraceInformation("WorkerRole1 is running");

            while (true)
            {
                int span = 0;

                switch (Microsoft.WindowsAzure.CloudConfigurationManager.GetSetting("Runtype") + "")
                {
                    case "AutoHourly-DeltaEvent":
                        span = 3600000;
                        break;

                    case "Auto-DeltaEvent":
                        span = 86400000;
                        break;

                    case "AutoHourly-Delta":
                        span = 3600000;
                        break;

                    case "AutoDelta":
                        span = 86400000;
                        break;

                    default:
                        span = 172800000;
                        break;
                }

                Thread.Sleep(span);

                ImportBlobtoDB();
            }
        }

        public override bool OnStart()
        {
            // Set the maximum number of concurrent connections
            ServicePointManager.DefaultConnectionLimit = 12;

            // For information on handling configuration changes
            // see the MSDN topic at http://go.microsoft.com/fwlink/?LinkId=166357.

            bool result = base.OnStart();

            Trace.TraceInformation("WorkerRole1 has been started");

            if (Microsoft.WindowsAzure.CloudConfigurationManager.GetSetting("RunonStart") + "" == "true")
                ImportBlobtoDB();

            return result;
        }

        public override void OnStop()
        {
            Trace.TraceInformation("WorkerRole1 is stopping");

            this.cancellationTokenSource.Cancel();
            this.runCompleteEvent.WaitOne();

            base.OnStop();

            Trace.TraceInformation("WorkerRole1 has stopped");
        }

        private async Task RunAsync(CancellationToken cancellationToken)
        {
            // TODO: Replace the following with your own logic.
            while (!cancellationToken.IsCancellationRequested)
            {
                Trace.TraceInformation("Working");
                await Task.Delay(1000);
            }
        }

        static void ImportBlobtoDB()
        {
            try
            {
                BlobParser parser = new BlobParser();
                parser.StorageConnString = GetConnectionString();
                parser.FilterType = Microsoft.WindowsAzure.CloudConfigurationManager.GetSetting("Eventtype") + "";
                parser.FilterContainer = Microsoft.WindowsAzure.CloudConfigurationManager.GetSetting("Container") + "";
                parser.FilterDate = Microsoft.WindowsAzure.CloudConfigurationManager.GetSetting("Date") + "";

                switch (Microsoft.WindowsAzure.CloudConfigurationManager.GetSetting("Runtype") + "")
                {
                    case "Eventtype":
                        parser.ParseEventtypewise();
                        break;

                    case "Full":
                        parser.ParseFull();
                        break;

                    case "Delta":
                        parser.ParseDelta();
                        break;

                    case "Date":
                        parser.ParseDatewise();
                        break;

                    case "Auto-DeltaEvent":
                        parser.FilterDate = System.DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd");
                        parser.ParseDelta();
                        break;

                    case "Auto-Delta":
                        parser.FilterDate = System.DateTime.Today.AddDays(-1).ToString("yyyy-MM-dd");
                        parser.ParseDatewise();
                        break;

                    case "AutoHourly-DeltaEvent":
                        parser.FilterDate = System.DateTimeOffset.Now.UtcDateTime.AddHours(-1).Date.ToString("yyyy-MM-dd");
                        parser.FilterTime = System.DateTimeOffset.Now.UtcDateTime.AddHours(-1).Hour.ToString();
                        parser.ParseHourlyDelta();
                        break;

                    case "AutoHourly-Delta":
                        parser.FilterDate = System.DateTimeOffset.Now.UtcDateTime.AddHours(-1).Date.ToString("yyyy-MM-dd");
                        parser.FilterTime = System.DateTimeOffset.Now.UtcDateTime.AddHours(-1).Hour.ToString();
                        parser.ParseHourwise();
                        break;

                    case "DeltaBetween":
                        parser.FilterDateFrom = Microsoft.WindowsAzure.CloudConfigurationManager.GetSetting("PullfromDate");
                        parser.FilterDateTo = Microsoft.WindowsAzure.CloudConfigurationManager.GetSetting("PulltoDate");
                        parser.ParseDeltaBetween();
                        break;

                    case "FullBetween":
                        parser.FilterDateFrom = Microsoft.WindowsAzure.CloudConfigurationManager.GetSetting("PullfromDate");
                        parser.FilterDateTo = Microsoft.WindowsAzure.CloudConfigurationManager.GetSetting("PulltoDate");
                        parser.ParseFullBetween();
                        break;

                    default:
                        break;
                }
            }
            catch (Exception ex)
            {
                //
            }
        }
        
        private static string GetConnectionString()
        {
            return Microsoft.WindowsAzure.CloudConfigurationManager.GetSetting("StorageConnectionString");
        }
    }
}
